package com.pww.movie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.pww.movie.domain.DTO.LoginDTO;
import com.pww.movie.domain.PO.User;
import com.pww.movie.domain.VO.LoginVO;
import com.pww.movie.service.IUserService;
import com.pww.movie.utils.JwtUtil;
import com.pww.movie.utils.Md5Util;
import com.pww.movie.utils.Result;
import jakarta.validation.constraints.Pattern;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;


@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping("/auth")
public class AuthController {


    private IUserService userService;

    private JwtUtil jwtUtil;

    private StringRedisTemplate stringRedisTemplate;


    /**
     * 登录
     *
     * @param
     * @return
     */
    @PostMapping("/login")
    public Result<LoginVO> login(@Pattern(regexp = "^.{2,16}$") String username, @Pattern(regexp = "^[a-zA-Z0-9]{2,16}$") String password) {
        User user = userService.lambdaQuery()
                .eq(User::getUsername, username)
                .one();
        log.info("用户名:{},密码:{}", username, password);
        if (user == null) {
            return Result.error("用户名不存在");
        }
        //密码校验
        if (Md5Util.getMD5String(password).equals(user.getPassword())) {
            HashMap<String, Object> claims = new HashMap<>();
            claims.put("id", user.getId());
            claims.put("username", user.getUsername());
            String token = JwtUtil.genToken(claims);
            log.info("JWT Token:{}", token);
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(token, token, 1, TimeUnit.HOURS);
            log.info("result:{}", Result.success(token));
            LoginVO loginVO = new LoginVO(token);
            return Result.success(loginVO);
        }
        return Result.error("密码错误");

    }


}

